package com.shuaigef.springbootinit.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuaigef.springbootinit.common.BaseResponse;
import com.shuaigef.springbootinit.common.ResultUtils;
import com.shuaigef.springbootinit.exception.BusinessException;
import com.shuaigef.springbootinit.model.dto.exercise.ExerciseJudgeRequest;
import com.shuaigef.springbootinit.model.dto.exercise.ExerciseSubmitRequest;
import com.shuaigef.springbootinit.model.entity.Exercise;
import com.shuaigef.springbootinit.model.entity.Paper;
import com.shuaigef.springbootinit.model.entity.UserExercisePaper;
import com.shuaigef.springbootinit.model.enums.ExerciseDifficulty;
import com.shuaigef.springbootinit.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 题目接口
 */
@RestController
@Slf4j
@RequestMapping("/exercise")
public class ExerciseController {
    @Resource
    private PaperService paperService;
    @Resource
    private ExerciseService exerciseService;
    @Resource
    private UserExercisePaperService userExercisePaperService;
    @Resource
    private UserService userService;

    /**
     * 查看题库
     */
    @PostMapping("/getPaper/{paperId}")
    public BaseResponse<Paper> get(@PathVariable("paperId") String id) {
        Paper paper =paperService.getPaper(id);
        return ResultUtils.success(paper);
    }

    /**
     * 查看所有题库
     */
    @PostMapping("/get/all")
    public BaseResponse<List<Paper>> getAll() {
        List<Paper> paperList=paperService.getList();
        return ResultUtils.success(paperList);
    }

    /**
     * 查看某门科目的题库
     */
    @PostMapping("/get/{course_id}")
    public BaseResponse<List<Paper>> getSubject(@PathVariable("course_id") String id) {
        List<Paper> list =paperService.getSubject(id);
        return ResultUtils.success(list);
    }

    /**
     * 根据id查看题目
     */
    @GetMapping("/getExercise/{id}")
    public BaseResponse<Exercise> getExercise(@PathVariable("id") String id) {
        Exercise exercise = exerciseService.getExerciseById(id);
        return ResultUtils.success(exercise);
    }

    /**
     * 提交答案
     */
    @PostMapping("/submit")
    public BaseResponse<Exercise> submit(@RequestBody ExerciseSubmitRequest exerciseSubmitRequest) {
        Exercise exercise = exerciseService.getBaseMapper().selectOne(new LambdaQueryWrapper<Exercise>()
                .eq(Exercise::getExerciseId, exerciseSubmitRequest.getExerciseId()));
        if (exercise == null) {
            throw new BusinessException(400, "该题目不存在");
        }
        UserExercisePaper userExercisePaper = UserExercisePaper.builder()
                .exerciseId(Integer.valueOf(exerciseSubmitRequest.getExerciseId()))
                .paperId(Integer.valueOf(exerciseSubmitRequest.getPaperId()))
                .isCorrect(exerciseSubmitRequest.getExerciseAnswer().equals(exercise.getExerciseAnswer()) ? 0 : 1)
                .userId(userService.getLoginUser().getUserId())
                .userAnswer(exerciseSubmitRequest.getExerciseAnswer())
                .build();
        //简答题就等待判断
        if ("简答题".equals(exerciseSubmitRequest.getExerciseType())) {
            userExercisePaper.setIsCorrect(2);
            userExercisePaperService.save(userExercisePaper);
            return ResultUtils.success();
        }
        if (!exercise.getExerciseAnswer().equals(exerciseSubmitRequest.getExerciseAnswer())) {
            //错误
            userExercisePaper.setIsCorrect(0);
            userExercisePaperService.save(userExercisePaper);
            throw new BusinessException(400, "答案错误");
        } else {
            //正确
            userExercisePaper.setIsCorrect(1);
            userExercisePaperService.save(userExercisePaper);
            return ResultUtils.success(exercise);
        }
    }


    /*
    /全面都是不完整版，需要看设计
     */


    /**
     * 查看学生未判断的简答题
     * 不完整版，还需后面修改接口
     * 可能需要学生id，班级id，或者说试卷id
     */
    @PostMapping("/getUnCorrect")
    public BaseResponse<UserExercisePaper> judge() {
        UserExercisePaper userExercisePaper = userExercisePaperService.getBaseMapper()
                .selectOne(new LambdaQueryWrapper<UserExercisePaper>()
                        .eq(UserExercisePaper::getIsCorrect, 2));
        if (userExercisePaper == null) {
            throw new BusinessException(400, "该题目不存在");
        }
        return ResultUtils.success(userExercisePaper);
    }

    /**
     * 先查看到学生未判断的简答题，老师打正确错误
     * 判题
     */
    @PostMapping("/judge")
    public BaseResponse<String> judge(@RequestBody ExerciseJudgeRequest exerciseJudgeRequest) {
        UserExercisePaper userExercisePaper = userExercisePaperService.getBaseMapper().selectOne(new LambdaUpdateWrapper<UserExercisePaper>().eq(UserExercisePaper::getRecordId, exerciseJudgeRequest.getRecordId()));
        userExercisePaper.setIsCorrect(Integer.valueOf(exerciseJudgeRequest.getIsCorrect()));
        userExercisePaperService.getBaseMapper().updateById(userExercisePaper);
        return ResultUtils.success("1".equals(exerciseJudgeRequest.getIsCorrect()) ? "正确" : "错误");
    }

    /**
     * 查看错题
     */
    @PostMapping("/getWrong")
    public BaseResponse<List<UserExercisePaper>> getWrong() {
        List<UserExercisePaper> userExercisePapers = userExercisePaperService.getBaseMapper()
                .selectList(new LambdaQueryWrapper<UserExercisePaper>()
                        .eq(UserExercisePaper::getIsCorrect, 0));
        if (userExercisePapers.isEmpty()) {
             throw new BusinessException(400, "该题目不存在");
        }
        return ResultUtils.success(userExercisePapers);
    }

    /**
     * 获取推荐题目
     */
    @GetMapping("/recommend")
    public BaseResponse<List<Exercise>> getRecommendExercises() {
        // 获取当前登录用户
        Integer userId = userService.getLoginUser().getUserId();
        List<Exercise> recommendedExercises = exerciseService.getRecommendExercises(userId);
        return ResultUtils.success(recommendedExercises);
    }

    /**
     * 分析学生哪个方面欠缺
     */
    @GetMapping("/analyze/weakness")
    public BaseResponse<Map<String, Object>> analyzeWeakness() {
        // 获取当前登录用户
        Integer userId = userService.getLoginUser().getUserId();
        Map<String, Object> analysis = exerciseService.analyzeWeakness(userId);
        return ResultUtils.success(analysis);
    }

    /**
     * 答题情况（答过题的百分比）
     * 卷子id
     */
    @GetMapping("/analyze/progress/{id}")
    public BaseResponse<Map<String, Object>> analyzeProgress(@PathVariable("id") String id) {
        if("".equals(id)){
            throw new BusinessException(400, "该卷子不存在");
        }
        // 获取当前登录用户
        Map<String, Object> analysis = exerciseService.analyzeProgress(id);
        return ResultUtils.success(analysis);
    }

    /**
     * 分页获取题目列表
     */
    @GetMapping("/list")
    public BaseResponse<Map<String, Object>> getExerciseList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer paperId,
            @RequestParam(required = false) Integer difficulty
    ) {
        LambdaQueryWrapper<Exercise> queryWrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(Exercise::getExerciseContent, keyword);
        }
        
        // 题目类型筛选
        if (StringUtils.isNotBlank(type)) {
            queryWrapper.eq(Exercise::getExerciseType, type);
        }
        
        // 难度筛选
        if (difficulty != null && difficulty >= 1 && difficulty <= 5) {
            try {
                // 根据数字难度获取对应的中文难度标签
                String difficultyStr = null;
                for (ExerciseDifficulty diff : ExerciseDifficulty.values()) {
                    if (diff.getLevel() == difficulty) {
                        difficultyStr = diff.getLabel();
                        break;
                    }
                }
                
                if (difficultyStr != null) {
                    // 打印难度筛选条件
                    log.info("难度筛选: difficulty={}, difficultyStr={}", difficulty, difficultyStr);
                    queryWrapper.eq(Exercise::getExerciseDifficulty, difficultyStr);
                } else {
                    log.warn("无效的难度值: {}", difficulty);
                }
            } catch (Exception e) {
                log.error("难度转换失败: difficulty={}, error={}", difficulty, e.getMessage());
            }
        }
        
        // 题库筛选
        if (paperId != null) {
            Paper paper = paperService.getById(paperId);
            if (paper != null && StringUtils.isNotBlank(paper.getPaperContent())) {
                String[] exerciseIds = paper.getPaperContent().split(",");
                queryWrapper.in(Exercise::getExerciseId, Arrays.asList(exerciseIds));
            }
        }

        // 分页查询
        Page<Exercise> exercisePage = exerciseService.page(new Page<>(page, size), queryWrapper);
        
        // 获取错误率
        List<Exercise> records = exercisePage.getRecords();
        if (!records.isEmpty()) {
            for (Exercise exercise : records) {
                // 打印每个题目的难度值
                log.info("题目难度: id={}, difficulty={}", exercise.getExerciseId(), exercise.getExerciseDifficulty());
                
                // 计算错误率
                LambdaQueryWrapper<UserExercisePaper> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserExercisePaper::getExerciseId, exercise.getExerciseId());
                long totalCount = userExercisePaperService.count(wrapper);
                
                wrapper.eq(UserExercisePaper::getIsCorrect, 0);
                long wrongCount = userExercisePaperService.count(wrapper);
                
                double errorRate = totalCount == 0 ? 0 : (double) wrongCount / totalCount;
                exercise.setExerciseSymbol(String.format("%.2f", errorRate));
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", records);
        result.put("total", exercisePage.getTotal());
        return ResultUtils.success(result);
    }

    /**
     * 批量获取题目错误率
     */
    @GetMapping("/error-rates")
    public BaseResponse<Map<Integer, Double>> getExerciseErrorRates(@RequestParam List<Integer> exerciseIds) {
        if (CollUtil.isEmpty(exerciseIds)) {
            return ResultUtils.success(new HashMap<>());
        }

        Map<Integer, Double> errorRates = new HashMap<>();
        
        for (Integer exerciseId : exerciseIds) {
            // 计算每个题目的错误率
            LambdaQueryWrapper<UserExercisePaper> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserExercisePaper::getExerciseId, exerciseId);
            long totalCount = userExercisePaperService.count(wrapper);
            
            wrapper.eq(UserExercisePaper::getIsCorrect, 0);
            long wrongCount = userExercisePaperService.count(wrapper);
            
            double errorRate = totalCount == 0 ? 0 : (double) wrongCount / totalCount;
            errorRates.put(exerciseId, errorRate);
        }

        return ResultUtils.success(errorRates);
    }

}

